#!/usr/bin/env python3
"""
Command line argument parser for the SERP API search tool.
"""

import argparse
import os
import sys

def parse_args():
    """Parse command line arguments."""
    parser = argparse.ArgumentParser(description='Search for papers in Google Scholar')
    parser.add_argument('--keyword', action='append', 
                        help='Search keyword (can be used multiple times for OR search)')
    parser.add_argument('-n', '--num', type=int, default=80,
                        help='Number of results to retrieve (default: 80)')
    parser.add_argument('--download', action='store_true',
                        help='Download papers (default: False)')
    parser.add_argument('--doi', action='store_true',
                        help='Extract DOIs and write to a new CSV file (default: False)')
    parser.add_argument('--filter', action='store_true',
                        help='Filter redundant papers and save to paper_info_filter.csv (default: False)')
    parser.add_argument('--validate-pdfs', action='store_true',
                        help='Validate all downloaded PDFs and save results to a cache file (default: False)')
    parser.add_argument('--retry', action='store_true',
                        help='List papers that failed to download for retry (default: False)')
    parser.add_argument('--arxiv', action='store_true',
                        help='Search arxiv.org for papers that failed to download and attempt to download them (default: False)')
    parser.add_argument('--pdf-fail', action='store_true',
                        help='List papers that have PDF download links but failed to download (default: False)')
    parser.add_argument('--acm', action='store_true',
                        help='List papers from dl.acm.org that failed to download (default: False)')
    parser.add_argument('--query', action='store_true',
                        help='Query download status and print information about failed downloads classified by source website')
    parser.add_argument('--precise', action='store_true',
                        help='Match keywords exactly (use quotes for phrases)')
    parser.add_argument('--import', metavar='FILE', dest='import_pdf',
                        help='Import PDF file from local system, identify its title and update status')
    parser.add_argument('--import-dir', metavar='DIR',
                        help='Import all PDF files from a directory, identify their titles and update status')
    parser.add_argument('--update', action='store_true',
                        help='Scan papers directory and update status of previously failed downloads that now exist')
    parser.add_argument('--project', metavar='PROJ_NAME',
                        help='Create a project directory to store all files related to this search')
    parser.add_argument('--check', action='store_true',
                        help='Check for redundant papers in the data directory (default: False)')
    parser.add_argument('-v', '--verbose', action='store_true',
                        help='Enable verbose logging (default: False)')
    return parser.parse_args()

def get_serp_api_key():
    """Get SERP API key from environment variables."""
    api_key = os.environ.get('SERP_API')
    if not api_key:
        print("Error: SERP_API environment variable not set")
        sys.exit(1)
    return api_key

def setup_project_directories(project_name):
    """Create project directory structure and return paths dictionary."""
    if not project_name:
        return {
            'base_dir': '',
            'data_dir': 'data',
            'papers_dir': 'papers'
        }
    
    # Create project parent directory
    project_parent_dir = 'project'
    os.makedirs(project_parent_dir, exist_ok=True)
    
    # Create project directory
    base_dir = os.path.join(project_parent_dir, project_name)
    data_dir = os.path.join(base_dir, 'data')
    papers_dir = os.path.join(base_dir, 'papers')
    
    # Create directories
    os.makedirs(base_dir, exist_ok=True)
    os.makedirs(data_dir, exist_ok=True)
    os.makedirs(papers_dir, exist_ok=True)
    
    print(f"Created project directory structure in: {base_dir}")
    
    return {
        'base_dir': base_dir,
        'data_dir': data_dir,
        'papers_dir': papers_dir
    } 